package cn.ming.wfchat.app.main;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.AppService;
import cn.ming.wfchat.app.me.activity.AutoActivity;
import cn.ming.wfchat.app.me.activity.CloudTagActivity;
import cn.ming.wfchat.app.me.activity.MyAssetsActivity;
import cn.ming.wfchat.app.me.activity.RealNameActivity;
import cn.ming.wfchat.app.me.activity.SetDlmmActivity;
import cn.ming.wfchat.app.me.activity.YsaqActivity;
import cn.ming.wfchat.app.me.activity.model.CertificationListbean;
import cn.ming.wfchat.kit.ChatManagerHolder;
import cn.ming.wfchat.kit.Config;
import cn.ming.wfchat.kit.WfcScheme;
import cn.ming.wfchat.kit.WfcWebViewActivity;
import cn.ming.wfchat.kit.dialog.CancelTheDealDialog;
import cn.ming.wfchat.kit.net.OKHttpHelper;
import cn.ming.wfchat.kit.qrcode.QRCodeActivity;
import cn.ming.wfchat.kit.third.utils.UIUtils;
import cn.ming.wfchat.kit.user.UserInfoActivity;
import cn.ming.wfchat.kit.user.UserViewModel;
import cn.ming.wfchat.kit.utils.Tools;
import cn.ming.wfchat.kit.widget.OptionItemView;
import cn.wildfirechat.model.UserInfo;

public class MeFragment extends Fragment {

    @BindView(R.id.meLinearLayout)
    LinearLayout meLinearLayout;
    @BindView(R.id.portraitImageView)
    ImageView portraitImageView;
    @BindView(R.id.nameTextView)
    TextView nameTextView;
    @BindView(R.id.accountTextView)
    TextView accountTextView;
    @BindView(R.id.ll_wdzc)
    OptionItemView llWdzc;
    @BindView(R.id.ll_ysaq)
    OptionItemView llYsaq;
    @BindView(R.id.ll_help)
    OptionItemView llHelp;
    @BindView(R.id.ll_auto)
    OptionItemView llAuto;
    @BindView(R.id.ll_out)
    OptionItemView llOut;
    @BindView(R.id.ll_zxwk)
    OptionItemView llZxwk;
    @BindView(R.id.ll_sfyz)
    OptionItemView llSfyz;
    @BindView(R.id.iv_code)
    ImageView iv_code;

    private UserViewModel userViewModel;
    private UserInfo userInfo;

    private Observer<List<UserInfo>> userInfoLiveDataObserver = new Observer<List<UserInfo>>() {
        @Override
        public void onChanged(@Nullable List<UserInfo> userInfos) {
            if (userInfos == null) {
                return;
            }
            for (UserInfo info : userInfos) {
                if (info.uid.equals(userViewModel.getUserId())) {
                    userInfo = info;
                    updateUserInfo(userInfo);
                    break;
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment_me, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void updateUserInfo(UserInfo userInfo) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.avatar_def)
                .transforms(new CenterCrop(), new RoundedCorners(UIUtils.dip2Px(getContext(), 10)));
        Glide.with(this)
                .load(userInfo.portrait)
                .apply(options)
                .into(portraitImageView);
        nameTextView.setText(userInfo.displayName);
        accountTextView.setText("账号: " + userInfo.mobile);
    }

    private void init() {
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        userViewModel.getUserInfoAsync(userViewModel.getUserId(), true)
                .observe(getViewLifecycleOwner(), info -> {
                    userInfo = info;
                    if (userInfo != null) {
                        updateUserInfo(userInfo);
                    }
                });
        userViewModel.userInfoLiveData().observeForever(userInfoLiveDataObserver);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        userViewModel.userInfoLiveData().removeObserver(userInfoLiveDataObserver);
    }

    @OnClick(R.id.meLinearLayout)
    void showMyInfo() {
        Intent intent = new Intent(getActivity(), UserInfoActivity.class);
        intent.putExtra("userInfo", userInfo);
        startActivity(intent);
    }

    @OnClick(R.id.ll_ysaq)
    void toYsaq() {
        Intent intent = new Intent(getActivity(), YsaqActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.ll_zxwk)
    void toZxwk() {
        certificationList();

    }

    @OnClick(R.id.ll_sfyz)
    void toSfyz() {
        Intent intent = new Intent(getActivity(), RealNameActivity.class);
        startActivity(intent);

    }

//    @OnClick(R.id.themeOptionItemView)
//    void theme() {
//        SharedPreferences sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
//        boolean darkTheme = sp.getBoolean("darkTheme", true);
//        new MaterialDialog.Builder(getContext()).items(R.array.themes).itemsCallback(new MaterialDialog.ListCallback() {
//            @Override
//            public void onSelection(MaterialDialog dialog, View v, int position, CharSequence text) {
//                if (position == 0 && darkTheme) {
//                    sp.edit().putBoolean("darkTheme", false).apply();
//                    restart();
//                    return;
//                }
//                if (position == 1 && !darkTheme) {
//                    sp.edit().putBoolean("darkTheme", true).apply();
//                    restart();
//                }
//            }
//        }).show();
//    }

    @OnClick(R.id.ll_wdzc)
    void setLlWdzc() {
        Intent intent = new Intent(getActivity(), MyAssetsActivity.class);
        startActivity(intent);
    }

    private void restart() {
        Intent i = getActivity().getApplicationContext().getPackageManager().getLaunchIntentForPackage(getActivity().getApplicationContext().getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }

    //    @OnClick(R.id.settintOptionItemView)
//    void setting() {
//        Intent intent = new Intent(getActivity(), SettingActivity.class);
//        startActivity(intent);
//    }
//
//    @OnClick(R.id.notificationOptionItemView)
//    void msgNotifySetting() {
//        Intent intent = new Intent(getActivity(), MessageNotifySettingActivity.class);
//        startActivity(intent);
//    }
    @OnClick(R.id.ll_help)
    void setLlHelp() {
        WfcWebViewActivity.loadUrl(getActivity(), "帮助中心", Config.APP_SERVER_ADDRESS + "/h5/help");
    }

    @OnClick(R.id.ll_out)
    void setLlOut() {
        SharedPreferences sp = getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        if (!sp.getBoolean("loginPassword", false)) {
            CancelTheDealDialog.newInstance().setTitle("提示").setContext("您还未设置登录密码，退出登录前请先设置登录密码！")
                    .setOnClickListener(new CancelTheDealDialog.OnClickListener() {
                        @Override
                        public void successful() {
                            Tools.jump(getActivity(), SetDlmmActivity.class, false);
                        }

                        @Override
                        public void cancel() {

                        }
                    }).show(getActivity());
        } else {
            //不要清除session，这样再次登录时能够保留历史记录。如果需要清除掉本地历史记录和服务器信息这里使用true
            ChatManagerHolder.gChatManager.disconnect(true, false);
            sp.edit().clear().apply();
            OKHttpHelper.clearCookies();
            Intent intent = new Intent(getContext(), SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            getActivity().finish();
        }
    }

    @OnClick(R.id.ll_auto)
    void setLlAuto() {
        Tools.jump(getActivity(), AutoActivity.class, false);
    }

    @OnClick(R.id.iv_code)
    void setIv_code() {
        UserInfo userInfo = userViewModel.getUserInfo(userViewModel.getUserId(), false);
        String qrCodeValue = WfcScheme.QR_CODE_PREFIX_USER + userInfo.mobile;
        startActivity(QRCodeActivity.buildQRCodeIntent(getActivity(), "二维码", userInfo.portrait, qrCodeValue));
    }

    void certificationList() {
        AppService.Instance().certificationList(new AppService.CertificationListCallback() {
            @Override
            public void onUiSuccess(CertificationListbean redPageListBean) {
                if (TextUtils.equals(redPageListBean.getStatus(), "SUCCESS")) {
                    Intent intent = new Intent(getActivity(), CloudTagActivity.class);
                    startActivity(intent);
                } else {
                    CancelTheDealDialog.newInstance().setTitle("提示").setOktext("去认证").setQtext("取消").
                            setContext("在线挖矿需要身份认证，是否去认证？").
                            setOnClickListener(new CancelTheDealDialog.OnClickListener() {
                                @Override
                                public void successful() {
                                    Intent intent = new Intent(getActivity(), RealNameActivity.class);
                                    startActivity(intent);
                                }

                                @Override
                                public void cancel() {

                                }
                            }).show(getActivity());
                }
            }

            @Override
            public void onUiFailure(int code, String msg) {
                Tools.showToast(getActivity(), msg);
            }
        });
    }

}

